import 'package:app/api/delivery/index.dart';
import 'package:app/api/material-pick/index.dart';
import 'package:app/api/pick/index.dart';
import 'package:app/components/index.dart';
import 'package:app/components/tree/treeItemButton.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:bruno/bruno.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class ContainerAdjust extends StatefulWidget {
  const ContainerAdjust({super.key});

  @override
  State<ContainerAdjust> createState() => ContainerAdjustState();
}

class ContainerAdjustState extends State<ContainerAdjust> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  final FocusNode _firstFocusNode = FocusNode();

  final FocusNode _secondFocusNode = FocusNode();

  String _code = "";

  String _station = "";

  String _pickCode = "";

  String _status = "";

  String _pickId = "";

  String _containerId = "";

  List<dynamic> _containerList = [];

  bool _isShow = false;

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
      setParams(ModalRoute.of(context)!.settings.arguments);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'code') {
      setState(() => _code = qrCode.toString());
    } else if (key == 'station') {
      setState(() => _station = qrCode.toString());
    }
  }

  /// 获取树形元素
  List<TreeItem> getTree() {
    return _containerList
        .map((item) => TreeItem(
                label: item['code'],
                expand: item['expand'],
                checked: item['checked'],
                children: getChildren(item['children'] ?? []),
                buttons: [
                  TreeItemButton(
                      label: '拆分',
                      onPressed: split,
                      isShow: StringUtils.isNotNull(item['children']) &&
                              item['children'].length > 0
                          ? true
                          : false),
                  TreeItemButton(
                      label: '拣配',
                      onPressed: packing,
                      isShow: _status == '0' ? true : false,
                      backgroundColor: Colors.green),
                  TreeItemButton(
                    label: '删除',
                    onPressed: remove,
                    backgroundColor: Colors.red,
                    isShow: _status == '0' ? true : false,
                  ),
                ]))
        .toList();
  }

  /// 获取子项
  List<TreeItem>? getChildren(List<dynamic> list) {
    if (StringUtils.isNull(list)) {
      return null;
    }
    return list
        .map((item) => TreeItem(
              label: item['code'],
              checked: item['checked'],
              buttons: [
                TreeItemButton(
                    label: '删除',
                    onPressed: remove,
                    isShow: _status == '0' ? true : false,
                    backgroundColor: Colors.red),
                TreeItemButton(
                    label: '拣配',
                    onPressed: remove,
                    isShow: _status == '0' ? true : false,
                    backgroundColor: Colors.green)
              ],
            ))
        .toList();
  }

  /// 删除
  void remove(index, childIndex, level) {
    Confirm.of(context).show('确定要删除么？', () {
      int id = level == 1
          ? _containerList[index]['id']
          : _containerList[index]['children'][childIndex]['id'];
      // 调用删除托盘接口
      MaterialPickApi.of(context).removeContainer(id.toString()).then((res) {
        if (res.data['code'] == 'success') {
          setState(() => level == 1
              ? _containerList.remove(_containerList[index])
              : _containerList[index]['children']
                  .remove(_containerList[index]['children'][childIndex]));
          Navigator.of(context).pop();
        }
      });
    });
  }

  /// 下拉
  void change(expand, index, item) {
    setState(() => _containerList[index]['expand'] =
        StringUtils.isNotNull(expand) ? !expand : false);
  }

  /// 单选
  void onCheck(checked, index, childIndex, leave) {
    if(_status != '10'){
      final params = leave == 1
          ? _containerList[index]
          : _containerList[index]['children'][childIndex];
      clearChecked();
      setCallbackValue(params, checked);
    }
  }

  /// 删除全部选中数据
  void clearChecked() {
    _containerList.forEach((item) {
      item['checked'] = false;
      if (StringUtils.isNotNull(item['children']) &&
          item['children'].length > 0) {
        item['children'].forEach((child) => child['checked'] = false);
      }
    });
  }

  /// 选中回显值
  void setCallbackValue(params, checked) {
    setState(() {
      params['checked'] = !checked;
      _code = params['code'];
      _station = params['station'] ?? "";
      _containerId =
          StringUtils.isNotNull(params['id']) ? params['id'].toString() : "";
    });
  }

  /// 拆分
  void split(index, childIndex, level) {
    setState(() {
      _containerList.addAll(_containerList[index]['children']);
      _containerList[index]['expand'] = false;
      _containerList[index].remove('children');
    });
  }

  void clear() {
    clearChecked();
    setState(() {
      _code = "";
      _station = "";
      _containerId = "";
    });
  }

  /// 确认
  void confirm() {
    Forms.validate(_formKey!).then((valid) async {
      if (valid) {
        Map<String, String> data = {
          'containerCode': _code,
          'station': _station,
          'pickCode': _pickCode,
          'containerId': _containerId
        };
        MaterialPickApi.of(context).addContainer(data).then((res) {
          if (StringUtils.isNotNull(res.data)) {
            setResultValue(res);
          }
        });
        clear();
        hideKeyBorder();
      }
    });
  }

  /// 设置返回值
  void setResultValue(res) {
    print(res);
    setState(() {
      _pickCode = res.data['data']['code'];
      _status = res.data['data']['status'];
      _pickId = res.data['data']['id'].toString();
      _isShow = res.data['data']['isShow'];
      _containerList = res.data['data']['container']
          .map((item) => {
                'id': item['id'],
                'code': item['container'],
                'station': item['station'],
                'status': item['status'],
                'expand': true,
                'check': false
              })
          .toList();
    });
  }

  /// 拣配
  void packing(index, childIndex, level) {
    final item = level == 1
        ? _containerList[index]
        : _containerList[index]['children'][childIndex];
    Navigator.pushNamed(context, "/packing", arguments: {
      'pickCode': _pickCode,
      'containerCode': item['code'],
      'station': item['station'],
      'pickId': _pickId
    });
  }

  /// 设置值
  void setValue(String key, String value) {
    switch (key) {
      case '_code':
        setState(() => _code = value);
        break;
      case '_station':
        setState(() => _station = value);
        break;
      case '_pickCode':
        setState(() => _pickCode = value);
        break;
      default:
        throw Exception("key error");
    }
  }

  /// 拣配完成 & 立即配送
  void finish() {
    final message = _status == '0' ? '确认要完成拣配么？' : '确定要立即配送么？';
    Confirm.of(context).show(message, () {
      if (_status == '0') {
        PickApi.of(context).finishPick(_pickId).then((res) {
          Navigator.of(context).pop();
          if (StringUtils.isNotNull(res.data) &&
              res.data['code'] == 'success') {
            pickById();
          }
        });
      } else if (_status == '10') {
        Delivery.of(context).immediately(_pickId).then((res) {
          Navigator.of(context).pop();
          if (StringUtils.isNotNull(res.data) && res.data['code'] == 'success') {
            Success.of(context).show('配送成功，请等待');
            clear();
            setState(() {
              _containerList = [];
              _status = "";
              _pickId = "";
              _pickCode = "";
            });
          }
        });
      }
    });
  }

  /// 查找拣配单
  void pickById() {
    PickApi.of(context).pickById(_pickId).then((res) {
      if (StringUtils.isNotNull(res.data)) {
        setResultValue(res);
      }
    });
  }

  String getStatus() {
    switch (_status) {
      case "0":
        return "拣配中";
      case "10":
        return "拣配完成";
      case "20":
        return "配送中";
      default:
        return "";
    }
  }

  /// 获取操作按钮
  List<Widget> getOperationButtons() {
    if (StringUtils.isNull(_status) || _status == "0") {
      return [
        Button(
          label: '清空',
          icon: Icons.delete_forever,
          onPressed: clear,
          fontColor: Colors.black,
          backgroundColor: Colors.white,
          borderColor: const Color.fromARGB(255, 133, 133, 133),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 10),
          child: Button(
            label: '确认',
            icon: Icons.add,
            onPressed: confirm,
            iconColor: Colors.white,
            fontColor: Colors.white,
            backgroundColor: const Color.fromARGB(255, 69, 228, 194),
            borderColor: const Color.fromARGB(255, 69, 228, 194),
          ),
        )
      ];
    }
    return [];
  }

  // 是否显示操作按钮
  Button? isShowOperation() {
    if (_status == "0" || _status == "10") {
      return Button(
        label: _status == '0' ? '拣配完成' : '立即配送',
        height: 60,
        onPressed: _status == '0' ? finish : _status == '10' && _isShow ? finish : null,
        fontSize: 20,
      );
    }
    return null;
  }

  /// 确认
  void onEntry() {
    Future.delayed(const Duration(seconds: 1), () {
      confirm();
    });
  }

  /// 设置参数
  void setParams(params) {
    setState(() {
      if(StringUtils.isNotNull(params)){
        _station = params['station']??'';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '物料拣配'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Horizontal(items: [
              HorizontalItem(
                label: '拣配单号：',
                value: _pickCode,
                fontWeight: FontWeight.w600,
              ),
              HorizontalItem(
                label: '状态：',
                value: getStatus(),
                valueBackground: const Color.fromARGB(255, 69, 228, 194),
                fontColor: Colors.white,
              )
            ]),
            Offstage(
              offstage: _status == '10',
              child: Group(
                title: '托盘信息',
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                      formKey: _formKey,
                      formItem: [
                        FormItem(
                          onEntry: (String value) => {
                            FocusScope.of(context).requestFocus(_secondFocusNode)
                          },
                          type: 'input',
                          labelWidth: 90,
                          focusNode: _firstFocusNode,
                          labelText: '托盘编号',
                          placeholder: '请扫描托盘编号',
                          filedName: 'code',
                          value: _code,
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          onChange: (value) => setValue('_code', value),
                          iconOnTap: () => scan('code'),
                          rules: const {
                            'code': [
                              {'required': true, 'message': '托盘编号不能为空'}
                            ]
                          },
                        ),
                        FormItem(
                          onEntry: (String value) {
                            onEntry();
                          },
                          type: 'input',
                          labelWidth: 90,
                          focusNode: _secondFocusNode,
                          labelText: '位        置',
                          placeholder: '请扫描站点位置',
                          value: _station,
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          iconOnTap: () => scan('station'),
                          onChange: (value) => setValue('_station', value),
                        ),
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 10, right: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: getOperationButtons(),
                      ),
                    )
                  ],
                ),
              ),
            ),
            Expanded(
                child: Tree(
                  button: isShowOperation(),
                  title: '托盘信息',
                  onCheck: onCheck,
                  onChange: change,
                  items: getTree(),
                )
            ),
          ],
        ),
      ),
    );
  }
}
